package com.example.myapplication.services;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.example.myapplication.R;

/**
 * @author sjh
 * @Description
 * @create 2022/3/3 9:04
 */
public class MyService extends Service {

    private static final String TAG = "sun";
    private NotificationManager notificationManager;
    private Notification notification;
    private boolean flag = true;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind: ");
        return super.onUnbind(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    //获取通知管理器
                    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                    //通知主体
                    notification = new NotificationCompat.Builder(MyService.this, "sun")
                            .setContentTitle("出事了！")
                            .setContentText("你得停止服务啊")
                            .setSmallIcon(R.drawable.ic_baseline_airplanemode_active_24)
                            .setAutoCancel(true)
                            .build();

                    //发送通知
                    notificationManager.notify(1, notification);
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        thread.start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate: ");

        super.onCreate();
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy: ");
        flag = false;
        super.onDestroy();
    }

}
